package com.heaven.study.singleton;

import java.util.Collections;
import java.util.List;

import com.google.common.collect.Lists;

public class App {

    private static List<Singleton> lstInstance = null;

    public static void main(String[] args) {
        try {
            // lstInstance = Lists.newArrayList(); // 非线程安全
            // lstInstance = new Vector<>(); //线程安全


             // 线程安全, 通过加持的方式，实现线程安全
            lstInstance = Lists.newArrayList();
            lstInstance = Collections.synchronizedList(lstInstance);

            for (int i = 0; i < 10; i++) {
                new Thread((new Runnable() {
                    @Override
                    public void run() {
                        // Singleton tmpInstance = LazySingleton.getInstance();
                        Singleton tmpInstance = HungrySingleton.getInstance();
                        if (tmpInstance == null) {
                            System.out.println("Result is null too..");

                        }
                        lstInstance.add(tmpInstance);
                    }
                })).start();
            }

            Thread.sleep(1000);

            System.out.println(lstInstance.size());

            Singleton instance = lstInstance.get(0);
            for (Singleton loopInstance : lstInstance) {
                if (instance == null) {
                    System.out.print("null.....");
                }
                if (instance.equals(loopInstance)) {
                    System.out.println("Same instance");
                } else {
                    System.out.println("Different instance");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error.....");
        }

    }

}